package com.hexiang.http;

import com.hexiang.domain.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CommonResponseHttpClient {

    @Resource
    private CloseableHttpClient closeableHttpClient;

    @Resource
    private RequestConfig defaultRequestConfig;

    public CommonResponse<Serializable> doGet(String url, Map<String, String> param, Map<String, String> headers, RequestConfig requestConfig) {
        CommonResponse<Serializable> commonResponse;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 装载配置信息
            if (null != requestConfig) {
                httpGet.setConfig(requestConfig);
            } else {
                httpGet.setConfig(defaultRequestConfig);
            }

            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpGet::setHeader);
            }
            // 执行请求
            response = closeableHttpClient.execute(httpGet);
            //处理响应结果
            commonResponse = handleResponse(response);
        } catch (Exception e) {
            commonResponse = handleException(e, url, headers, param);
        } finally {
            closeResource(response);
        }
        log.info("doGetSuc,url:{},headers:{},param:{},commonResponse:{}", url, headers, param, commonResponse);
        return commonResponse;
    }

    public CommonResponse<Serializable> doGet(String url) {
        return doGet(url, null, null, null);
    }

    public CommonResponse<Serializable> doGet(String url, RequestConfig requestConfig) {
        return doGet(url, null, null, requestConfig);
    }

    public CommonResponse<Serializable> doGet(String url, Map<String, String> param) {
        return doGet(url, param, null, null);
    }

    public CommonResponse<Serializable> doPost(String url, Map<String, String> param) {
        return doPost(url, param, null, null);
    }

    public CommonResponse<Serializable> doPost(String url, Map<String, String> param, Map<String, String> headers, RequestConfig requestConfig) {
        CommonResponse<Serializable> commonResponse;
        CloseableHttpResponse response = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 装载配置信息
            if (null != requestConfig) {
                httpPost.setConfig(requestConfig);
            } else {
                httpPost.setConfig(defaultRequestConfig);
            }

            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPost::setHeader);
            }
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
            }

            // 执行http请求
            response = closeableHttpClient.execute(httpPost);
            //处理响应结果
            commonResponse = handleResponse(response);
        } catch (Exception e) {
            commonResponse = handleException(e, url, headers, param);
        } finally {
            closeResource(response);
        }

        return commonResponse;
    }

    private CommonResponse<Serializable> handleResponse(CloseableHttpResponse response) throws IOException {
        CommonResponse<Serializable> commonResponse;
        if (null != response) {
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                commonResponse = CommonResponse.builder().body(resultString).succ(true).build();
            } else {
                commonResponse = CommonResponse.builder().code(response.getStatusLine().getStatusCode()).msg("http服务调用报错").succ(false).build();
            }
        } else {
            commonResponse = CommonResponse.builder().code(500).msg("http服务无响应结果").succ(false).build();
        }
        return commonResponse;
    }

    private CommonResponse<Serializable> handleException(Exception e, String url, Map<String, String> headers, Object param) {
        CommonResponse<Serializable> commonResponse;
        if (e instanceof SocketTimeoutException) {
            log.error("socketTimeoutException url:{},headers:{},param:{},cause :", url, headers, param, e);
            commonResponse = CommonResponse.builder().code(504).msg("http服务调用超时").succ(false).build();
        } else if (e instanceof IOException) {
            log.error("IOException url:{},headers:{},param:{},cause :", url, headers, param, e);
            commonResponse = CommonResponse.builder().code(500).msg("http服务调用报错").succ(false).build();
        } else if (e instanceof URISyntaxException) {
            log.error("URISyntaxException url:{},headers:{},param:{},cause :", url, headers, param, e);
            commonResponse = CommonResponse.builder().code(400).msg("URL地址格式有问题").succ(false).build();
        } else {
            log.error("Exception url:{},headers:{},param:{},cause :", url, headers, param, e);
            commonResponse = CommonResponse.builder().code(500).msg("http服务调用报错").succ(false).build();
        }
        return commonResponse;
    }

    private void closeResource(CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            log.error("closeResourceErr", e);
        }
    }

    public CommonResponse<Serializable> doPost(String url) {
        return doPost(url, null, null, null);
    }

    public CommonResponse<Serializable> doPostJson(String url, String json, Map<String, String> headers, RequestConfig requestConfig) {
        CommonResponse<Serializable> commonResponse;

        CloseableHttpResponse response = null;
        try {

            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 装载配置信息
            if (null != requestConfig) {
                httpPost.setConfig(requestConfig);
            } else {
                httpPost.setConfig(defaultRequestConfig);
            }
            //设置http头部
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPost::setHeader);
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = closeableHttpClient.execute(httpPost);
            //处理响应结果
            commonResponse = handleResponse(response);
        } catch (Exception e) {
            commonResponse = handleException(e, url, headers, json);
        } finally {
            closeResource(response);
        }
        return commonResponse;
    }

    public CommonResponse<Serializable> doDelete(String url) {
        return doDelete(url, null, null);
    }

    public CommonResponse<Serializable> doDelete(String url, Map<String, String> headers, RequestConfig requestConfig) {
        CommonResponse<Serializable> commonResponse = null;

        CloseableHttpResponse response = null;
        try {
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(url);
            // 装载配置信息
            if (null != requestConfig) {
                httpDelete.setConfig(requestConfig);
            } else {
                httpDelete.setConfig(defaultRequestConfig);
            }
            httpDelete.setConfig(requestConfig);
            //设置http头部
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpDelete::setHeader);
            }
            // 执行http请求
            response = closeableHttpClient.execute(httpDelete);
            //处理响应结果
            commonResponse = handleResponse(response);
        } catch (Exception e) {
            commonResponse = handleException(e, url, headers, null);
        } finally {
            closeResource(response);
        }
        return commonResponse;
    }

    public CommonResponse<Serializable> doPut(String url, String json) {
        return doPut(url, json, null, null);
    }

    public CommonResponse<Serializable> doPut(String url, String json, Map<String, String> headers, RequestConfig requestConfig) {
        CommonResponse<Serializable> commonResponse;

        CloseableHttpResponse response = null;
        try {
            // 创建httpPut请求
            HttpPut httpPut = new HttpPut(url);
            // 装载配置信息
            if (null != requestConfig) {
                httpPut.setConfig(requestConfig);
            } else {
                httpPut.setConfig(defaultRequestConfig);
            }
            //设置http头部
            if (headers != null && !headers.isEmpty()) {
                headers.forEach(httpPut::setHeader);
            }
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpPut.setEntity(stringEntity);
            // 装载配置信息
            httpPut.setConfig(requestConfig);
            // 执行http请求
            response = closeableHttpClient.execute(httpPut);
            //处理响应结果
            commonResponse = handleResponse(response);
        } catch (Exception e) {
            commonResponse = handleException(e, url, headers, json);
        } finally {
            closeResource(response);
        }
        return commonResponse;
    }
}